<?php
namespace app\admin\controller;
use mylib\Delimg;
use think\Image;

class Banner extends Init
{

    public function index()
    {
        $banner = db('banner')->paginate();
        $this->assign("banner", $banner);
        return view();
    }
    public function add()
    {

        if(request()->isPost()) {
            $data['b_link'] = input('b_link');

            $file = request()->file('image');
            if($file) {
                $upload_path = config('upload.path');

                $info = $file->rule('uniqid')->move($upload_path);
                if ($info) {
                    $savename = $info->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
                $data['b_img'] = $savename;

                if (db('banner')->insert($data)) {
                    $this->redirect('banner/index');
                } else {
                    return $this->error('添加失败！');
                }
            }else{
                $this->error('请选择上传图片');
            }


        }

    }


    public function edit(){
        $id = input('id');
        $banner = db('banner')->where('b_id',$id)->find();
        $this->assign("banner", $banner);

        if(request()->isPost()){
            $data['b_link'] = input('b_link');

            //删除原图片
            $delimg = new Delimg();
            $delimg->delupimg('banner','b_id',$id,'b_img',".jpg",'_500_200.jpg');

            //增加新的图片
            $file = request()->file('image');
            $upload_path = config('upload.path');

            $info = $file->rule('uniqid')->move($upload_path);
            if($info){
                $savename = $info->getSaveName();
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
            $data['b_img'] = $savename;


            if(db('banner')->where('b_id',$id)->update($data)){
                $this->redirect('banner/index');
            }else{
                return $this->error('修改失败！');
            }
        }
        return view();
    }

    public function del(){
        $id = input('id');
        $delimg = new Delimg();
        $delimg->delupimg('banner','b_id',$id,'b_img',".jpg",'_500_200.jpg');


        if(db('banner')->where('b_id',$id)->delete()){
            $this->redirect('banner/index');
        }else{
            return $this->error('删除失败！');
        }
    }



    public function delall(){
        $data = input('post.');

        $arrdel = $data['idarr'];
        $delimg = new Delimg();
        $delimg->delAllimg('banner','b_id',$arrdel,'b_img',".jpg",'_500_200.jpg');

        if(request()->isPost()) {
            foreach ($arrdel as $id){
                db('banner')->where('b_id',$id)->delete();
            }
            $this->redirect('banner/index');
        }
    }

}